package com.easy.car.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easy.common.bean.Car;
import com.easy.common.service.ICarService;
import com.easy.common.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@CrossOrigin//允许跨域的
@RequestMapping("/car")
public class CarController {
    @Autowired
    ICarService carService;
    //查询单个
    @GetMapping("{id}")
    public Result getCarById(@PathVariable("id") Integer id) {
        return Result.success(carService.getCarById(id));
    }
    //查询所有
    @PostMapping("/list")
    public Result getAll(@RequestBody Car car) {
        return Result.success(carService.getAll(car));
    }
    //新增
    @PostMapping
    public Result addCar(@RequestBody Car car) {
        // 手动设置注册时间
        car.setRegister_time(LocalDateTime.now());
        int result = carService.addCar(car);
        return result > 0 ? Result.success("添加成功", null) : Result.fail(500, "添加失败");
    }
    //修改
    @PutMapping
    public Result updateCar(@RequestBody Car car) {
        int result = carService.updateCar(car);
        return result > 0 ? Result.success("更新成功", null) : Result.fail(500, "更新失败");
    }
    //删除
    @DeleteMapping("{id}")
    public Result deleteCar(@PathVariable("id") Integer id) {
        int result = carService.deleteCar(id);
        return result > 0 ? Result.success("删除成功", null) : Result.fail(500, "删除失败");
    }
    
    //分页查询
    @PostMapping("page")
    public Result getPage(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, @RequestBody(required = false) Car car) {
        IPage<Car> page = new Page<>(pageNum, pageSize);
        if (car == null) {
            car = new Car();
        }
        return Result.success(carService.getPage(car, page));
    }
}
